package net.algid.purchase.DAO;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.DriverManager;


public class DAOFactory {

	private Connection connection;
	private SupplierDAO suplierDAO;
	private PurchaseDAO purchaseDAO;
	private UnitDAO unitDAO;
	private GoodDAO goodDAO;
	private CustomerDAO customerDAO;

	public SupplierDAO getSupplierDAO() throws SQLException {
		if (suplierDAO != null) {
			return suplierDAO;
		}
		suplierDAO = new SupplierDAO(getConnection());
		return suplierDAO;
	}

	public PurchaseDAO getPurchaseDAO() throws SQLException {
		if (purchaseDAO != null) {
			return purchaseDAO;
		}
		purchaseDAO = new PurchaseDAO(getConnection());
		return purchaseDAO;
	}
	
	public UnitDAO getUnitDAO() throws SQLException {
		if (unitDAO != null) {
			return unitDAO;
		}
		unitDAO = new UnitDAO(getConnection());
		return unitDAO;
	}
	
	public GoodDAO getGoodDAO() throws SQLException {
		if (goodDAO != null) {
			return goodDAO;
		}
		goodDAO = new GoodDAO(getConnection());
		return goodDAO;
	}
 
	public CustomerDAO getCustomerDAO() throws SQLException {
		if (customerDAO != null) {
			return customerDAO;
		}
		customerDAO = new CustomerDAO(getConnection());
		return customerDAO;
	}
	
	public Connection getConnection() throws SQLException {
		if (connection != null) {
			return connection;
		} else {
			try {
				Class.forName("org.h2.Driver");
				connection = DriverManager.getConnection(
						"jdbc:h2:C:\\h2\\purchase", "sa", "");
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return connection;
		}
	}

	public void closeConnection() {
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
